package com.scs.application.modules.print.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.scs.application.core.consts.Const;
import com.scs.application.core.exception.BusinessException;
import com.scs.application.core.query.QueryContext;
import com.scs.application.core.service.BaseServiceImpl;
import com.scs.application.core.service.IBaseFileService;
import com.scs.application.core.utils.BeanUtils;
import com.scs.application.core.utils.FileUtils;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.modules.print.dto.TemplateDTO;
import com.scs.application.modules.print.entity.Field;
import com.scs.application.modules.print.mapper.FieldMapper;
import com.scs.application.modules.print.service.FieldService;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Description:打印数据文件操作
 */
@Slf4j
@Service
public class FileFieldServiceImpl extends BaseServiceImpl<FieldMapper, Field> implements FieldService, IBaseFileService {
    @Autowired
    private FileTemplateServiceImpl fileTemplateService;

    @Override
    public boolean removeCascadeById(Serializable id) {
        List<TemplateDTO> templateDTOS = fileTemplateService.getDTOList();
        for (TemplateDTO templateDTO : templateDTOS) {
            if (templateDTO.getFieldDTOS() == null || templateDTO.getFieldDTOS().isEmpty()) {
                continue;
            }
            for (TemplateDTO.FieldDTO fieldDTO : templateDTO.getFieldDTOS()) {
                if (id.equals(fieldDTO.getId())) {
                    templateDTO.getFieldDTOS().remove(fieldDTO);
                    String result = JSON.toJSONString(templateDTO, SerializerFeature.PrettyFormat);
                    String fileNameWithPath = Const.PRINT_TEMP_SRC + templateDTO.getBusType() + ".json";
                    FileUtils.writeTxtFile(fileNameWithPath, result);
                    break;
                }
            }
        }
        return true;
    }

    @Override
    public Field getById(Serializable id) {
        List<TemplateDTO> templateDTOS = fileTemplateService.getDTOList();
        Field field = new Field();
        for (TemplateDTO templateDTO : templateDTOS) {
            if (templateDTO.getFieldDTOS() == null || templateDTO.getFieldDTOS().isEmpty()) {
                continue;
            }
            for (TemplateDTO.FieldDTO fieldDTO : templateDTO.getFieldDTOS()) {
                if (id.equals(fieldDTO.getId())) {
                    BeanUtils.copyProperties(fieldDTO, field);
                    break;
                }
            }
        }
        return field;
    }

    @Override
    public boolean removeCascadeByIds(Collection<? extends Serializable> idList) {
        for (Serializable id : idList) {
            removeCascadeById(id);
        }
        return true;
    }

    @Override
    public Page<Field> page(QueryContext context) {
        List<Field> fields = list(context);
        return filePage(context, fields);
    }

    @Override
    public List<Field> getByTemplateId(String templateId) {
        QueryContext context = new QueryContext();
        context.setParams(Maps.newHashMap());
        context.getParams().put("templateId", templateId);
        return list(context);
    }

    @Override
    public List<Field> list() {
        QueryContext context = new QueryContext();
        return list(context);
    }

    @Override
    public List<Field> list(QueryContext context) {
        List<TemplateDTO> templateDTOS = fileTemplateService.getDTOList();
        if (templateDTOS == null && templateDTOS.isEmpty()) {
            return null;
        }
        if (context != null && context.getParams() != null && !context.getParams().isEmpty()) {
            String templateId = context.getParams().get("templateId") == null ? "" : context.getParams().get("templateId").toString();
            if (StringUtils.isEmpty(templateId)) {
                return null; //不支持没有传入类型的查询
            }
            String strType = context.getParams().get("type") == null ? "" : context.getParams().get("type").toString();
            Optional<TemplateDTO> optTemp = templateDTOS.stream().filter(temp -> templateId.equalsIgnoreCase(temp.getId())).findFirst();
            if (optTemp.isPresent()) {
                List<TemplateDTO.FieldDTO> fieldDTOS = optTemp.get().getFieldDTOS();
                if (fieldDTOS == null || fieldDTOS.isEmpty()) {
                    return null;
                }
                fieldDTOS = fieldDTOS.stream().filter(fieldDTO -> Strings.isEmpty(strType) || strType.equalsIgnoreCase(fieldDTO.getType())).collect(Collectors.toList());
                if (fieldDTOS == null || fieldDTOS.isEmpty()) {
                    return null;
                }
                List<Field> fields = Lists.newArrayListWithCapacity(fieldDTOS.size());
                for (TemplateDTO.FieldDTO fieldDTO : fieldDTOS) {
                    Field field = new Field();
                    BeanUtils.copyProperties(fieldDTO, field);
                    fields.add(field);
                }
                return fields;
            }
        } else { //获取所有的
            List<Field> fields = Lists.newArrayList();
            for (TemplateDTO templateDTO : templateDTOS) {
                if (templateDTO.getFieldDTOS() != null && !templateDTO.getFieldDTOS().isEmpty()) {
                    templateDTO.getFieldDTOS().forEach(fieldDTO -> {
                        Field field = new Field();
                        BeanUtils.copyProperties(fieldDTO, field);
                        fields.add(field);
                    });
                }
            }
            return fields;
        }
        return null;
    }

    @Override
    public <Field> boolean saveBatch(Class<Field> modelClass, Collection<Field> entityList, int batchSize) {
        return false;
    }

    @Override
    public boolean saveOrUpdate(Field field) {
        if (field == null || StringUtils.isEmpty(field.getTemplateId())) {
            BusinessException.throwValidFail("缺少参数，请至少选择一列有效属性");
        }
        TemplateDTO templateDTO = fileTemplateService.getDTOById(field.getTemplateId());

        if (templateDTO == null) {
            BusinessException.throwValidFail("未找到相关配置模板，请刷新重试");
        }

        File path = new File(Const.PRINT_TEMP_SRC);
        if (!path.exists()) {
            path.mkdirs();
        }

        TemplateDTO.FieldDTO fieldDTO = new TemplateDTO.FieldDTO();
        if (field.getId() == null) {
            field.setId(StringUtils.getIdStr());
        }
        BeanUtils.copyProperties(field, fieldDTO);

        if (templateDTO.getFieldDTOS() != null && templateDTO.getFieldDTOS().size() > 0) {
            templateDTO.getFieldDTOS().stream().filter(fieldDTO1 -> field.getId().equalsIgnoreCase(fieldDTO1.getId()))
                    .findAny().ifPresent(fieldDTO1 -> {
                templateDTO.getFieldDTOS().remove(fieldDTO1);
            });
        } else {
            templateDTO.setFieldDTOS(Lists.newArrayList());
        }

        templateDTO.getFieldDTOS().add(fieldDTO);

        String fileNameWithPath = Const.PRINT_TEMP_SRC + templateDTO.getBusType() + ".json";
        String result = JSON.toJSONString(templateDTO, SerializerFeature.PrettyFormat);
        FileUtils.writeTxtFile(fileNameWithPath, result);
        return true;
    }


    @Override
    public Boolean isSupport(Boolean flagProject) {
        return !flagProject;
    }
}

